package me.heyclock.hl.recordwriter.tools;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;

import java.io.File;

/**
 * Created by hl on 2018/4/3.
 */

public class AppUtils {
    private static final String RW_ROOT_PATH = "/sdcard/recordwriter/";
    private static final String RW_AUDIO_ROOT_PATH = RW_ROOT_PATH + "audio/";
    ///< 外部使用的不带"/"
    public static String RW_AUDIO_PATH = RW_AUDIO_ROOT_PATH + "default";
    public static final String RW_AUDIO_TEMP_PATH = RW_AUDIO_ROOT_PATH + "temp";

    /**
     * 初始化APP目录
     * @param userName
     */
    public static void initAppPath(String userName){
        if (null != userName && !userName.equals("")){
            RW_AUDIO_PATH = RW_AUDIO_ROOT_PATH + userName;
        }
        File file = new File(RW_AUDIO_PATH);
        if (!file.exists()){
            file.mkdirs();
        }
        file = new File(RW_AUDIO_TEMP_PATH);
        if (!file.exists()){
            file.mkdirs();
        }
    }

    /**
     * 获取本地软件版本号
     */
    public static int getLocalVersion(Context ctx) {
        int localVersion = 0;
        try {
            PackageInfo packageInfo = ctx.getApplicationContext()
                    .getPackageManager()
                    .getPackageInfo(ctx.getPackageName(), 0);
            localVersion = packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            return -1;
        }
        return localVersion;
    }

    /**
     * 获取本地软件版本号名称
     */
    public static String getLocalVersionName(Context ctx) {
        String localVersion = "";
        try {
            PackageInfo packageInfo = ctx.getApplicationContext()
                    .getPackageManager()
                    .getPackageInfo(ctx.getPackageName(), 0);
            localVersion = packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            return "";
        }
        return localVersion;
    }

    /*
     * 採用了新的办法获取APK图标。之前的失败是由于android中存在的一个BUG,通过
     * appInfo.publicSourceDir = apkPath;来修正这个问题，详情參见:
     * http://code.google.com/p/android/issues/detail?id=9151
     */
    public static int getApkVersionCode(Context context, String apkPath) {
        PackageManager pm = context.getPackageManager();
        PackageInfo info = pm.getPackageArchiveInfo(apkPath,
                PackageManager.GET_ACTIVITIES);
        if (info != null) {
            ApplicationInfo appInfo = info.applicationInfo;
            appInfo.sourceDir = apkPath;
            appInfo.publicSourceDir = apkPath;
            try {
                return info.versionCode;
            } catch (OutOfMemoryError e) {
                return -1;
            }
        }
        return -1;
    }

    /**
     * 获取设备型号
     * @return
     */
    public static String getModel(){
        return Build.MODEL;
    }
}
